<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/1/24
 * Time: 17:08
 */

namespace app\index\controller;


use app\common\utils\WeChatUtils;
use app\index\logic\UserLogic;
use think\Config;
use think\Controller;
use think\Log;

class WechatMsg extends Controller
{
    private $utils;

    public function __construct()
    {
        $we_chat = Config::get('WeChat');
        $this->utils = new WeChatUtils($we_chat['app_id'], $we_chat['app_secret'], $we_chat['token']);
    }

    public function getUtils()
    {
        return $this->utils;
    }

    //接收微信消息
    public function receiveMsg(){
        $xml_str = file_get_contents("php://input");
        Log::write($xml_str);
//         如果没有post数据，则响应空字符串表示结束
        if (empty($xml_str)) {
            die ('');
        }
        // 解析该xml字符串，利用simpleXMLhttp://101.132.27.131/
        libxml_disable_entity_loader(true);//禁止xml实体解析，防止xml注入
        Log::write('Begin','WARN');
        $request_xml = simplexml_load_string($xml_str, 'SimpleXMLElement', LIBXML_NOCDATA);//
        Log::write('in-----');
        // 判断该消息的类型通过元素：MsgType
        switch ($request_xml->MsgType) {
            case 'event': //事件类型
                //判断具体的事件类型（关注，取消，点击）
                $event = $request_xml->Event;
                if('SCAN' == $event){
                    //扫描二维码事件
                    $this->_doQRCode($request_xml);
                    Log::write('扫描二维码事件','WARN');
                }else if('subscribe' == $event){
                    Log::write('EventKey:'.$request_xml->EventKey);
                    $array = explode('_',$request_xml->EventKey);
                    if(count($array) == 2 && !empty($array[1])){
                        $note_id = $array[1];
                        $this->bindNote($note_id,$request_xml->FromUserName,$request_xml->ToUserName);
                    }
                }
                break;
            case 'text': // 文本消息
//                $this->_doText($request_xml);
                break;
        }
    }

    //发送图文详情
    private function sendNews($media_id,$openId,$ToUserName){
        $resource = $this->utils->getResourceByMediaId($media_id);
        $items = array();
//        $item['title'], $item['desc'], $item['picurl'], $item['url']
        foreach ($resource->news_item as $key => $value){
            $items[] = array(
                'title' => $value->title
            ,'desc' => $value->digest
            ,'picurl' => $value->thumb_url
            ,'url'   => $value->url
            );
        }
        $this->utils->msgNews($ToUserName,$openId,$items);
    }


    /**
     * 用于第一次验证uURL合法性
     */
    public function firstVaild()
    {
        //检验签名的合法性
        if ($this->_checkSignature()) {
            //签名合法，告知微信公众平台服务器
            echo $_GET['echostr'];
            exit;
        }
    }

    /**
     * 验证签名
     * @return bool
     */
    private function _checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $we_chat = Config::get('WeChat');
        $token = $we_chat['token'];
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /***
     * 处理二维码事件推送
     * @param $request_xml 微信事件推送的xml对象
     */
    private function _doQRCode($request_xml){
        $note_id = $request_xml->EventKey;//签id
        $openId = $request_xml->FromUserName;//openid
        $this->bindNote($note_id,$openId,$request_xml->ToUserName);
//        $this->utils->msgText($openId,$request_xml->ToUserName,'绑定成功,http://www.jipintc.com/');
    }


    private function bindNote($note_id,$openId,$ToUserName){
        $openId = ''.$openId;
        $note_id = ''.$note_id;
        $logic = new UserLogic();
        $result = $logic->bindNote($openId,$note_id);
        $item['title'] = '欢迎来到上善签！';
        $item['picurl'] = 'http://'.$_SERVER['HTTP_HOST'].'/images/wechat_bind_bg.jpg';
        $item['url'] = $_SERVER['HTTP_HOST'];
        if($result['status'] == 1){
            $item['desc'] = '绑定签成功！';
        }else{
            $item['desc'] = '绑定签失败！';
        }
        $item_list[0] = $item;
        $this->utils->msgNews($ToUserName,$openId,$item_list);
    }


    public function doSubscribe($openId,$ToUserName){

        $re = $this->utils->getNewsList();
        $item['title'] = $re->title;
        $item['desc'] = $re->digest;
        $item['picurl']  = $re->thumb_url;
        $item['url'] = $re->url;
        $item_list[0] = $item;
        $this->utils->msgNews($ToUserName,$openId,$item_list);
    }
}